package com.rmiad.controller;

import org.noear.snack.ONode;
import org.noear.solon.Utils;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Get;
import org.noear.solon.annotation.Mapping;
import org.noear.solon.annotation.Post;
import org.noear.solon.core.handle.Result;
import org.noear.solon.core.handle.UploadedFile;
import org.noear.solon.hotplug.PluginManager;

import java.io.File;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author wyl
 * @date 2025年02月23日 下午8:34
 */
@Controller()
@Mapping("plugin")
public class PluginManagerController {

    /**
     * 获取所有已加载插件列表
     */
    @Get
    @Mapping("list")
    public Result<List<ONode>> list() {
        List<ONode> plugins = PluginManager.getPlugins().stream().map(pluginInfo -> {
            String name = pluginInfo.getName();
            int lastDotIndex = pluginInfo.getFile().getName().lastIndexOf('-');
            return ONode.newObject().set("name", name)
                    .set("version", pluginInfo.getFile().getName().substring(lastDotIndex + 1, pluginInfo.getFile().getName().lastIndexOf('.')));
        }).collect(Collectors.toList());
        return Result.succeed(plugins);
    }

    /**
     * add
     */
    @Post
    @Mapping("add")
    public Result add(UploadedFile file) {
        try {
            File rootFile = Utils.getFile("./plugins");
            if (!rootFile.exists()) {
                rootFile.mkdirs();
            }
            file.transferTo(Paths.get(rootFile.getAbsolutePath(), file.getName()).toFile());
            // 新增插件
            String fileName = file.getName();
            PluginManager.add(fileName.substring(0, fileName.lastIndexOf('-')), Paths.get(rootFile.getAbsolutePath(), file.getName()).toFile());
            PluginManager.start(fileName.substring(0, fileName.lastIndexOf('-')));
        } catch (Exception e) {
            return Result.failure("插件新增失败: " + e.getMessage());
        }
        return Result.succeed();
    }

    /**
     * add
     */
    @Post
    @Mapping("remove")
    public Result remove(String name, String version) {
        try {
            PluginManager.unload(name);
            PluginManager.remove(name);
            File rootFile = Utils.getFile("./plugins");
            Paths.get(rootFile.getAbsolutePath(), name + "-" + version + ".jar").toFile().delete();
        } catch (Exception e) {
            return Result.failure("插件新增失败: " + e.getMessage());
        }
        return Result.succeed();
    }

}
